package org.anyin.gitee.shiro.shiro;

import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.anyin.gitee.shiro.base.BusinessCodeEnum;
import org.anyin.gitee.shiro.base.BusinessException;
import org.anyin.gitee.shiro.base.Response;
import org.anyin.gitee.shiro.base.SpringContext;
import org.anyin.gitee.shiro.service.ITokenService;
import org.anyin.gitee.shiro.utils.RequestIdUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Slf4j
public class TokenFilter extends AuthenticatingFilter {

    private static final String X_TOKEN = "X-Token";

    private ITokenService tokenService = null;

    /**
     * 创建Token, 支持自定义Token
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = this.getToken((HttpServletRequest)servletRequest);
        if(ObjectUtils.isEmpty(token)){
            log.error("token is empty");
            return null;
        }
        return new ShiroToken(token);
    }

    /**
     * 兼容跨域
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token = this.getToken(request);
        if(ObjectUtils.isEmpty(token)){
            this.responseException(request, response, BusinessCodeEnum.USER_UN_LOGIN.getException());
            return false;
        }

        // 校验Token的有效性
        if(tokenService == null){
            tokenService = SpringContext.getBean(ITokenService.class);
        }

        if(!tokenService.check(token)){
            this.responseException(request, response, BusinessCodeEnum.USER_UN_LOGIN.getException());
        }

        // 根据token获取用户信息，会执行 TokenRealm#doGetAuthenticationInfo 方法
        return executeLogin(servletRequest, servletResponse);
    }

    @SneakyThrows
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        this.responseException(request, response, BusinessCodeEnum.TOKEN_INVALID.getException());
        return false;
    }

    private void responseException(HttpServletRequest request, HttpServletResponse response, BusinessException ex) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        Response resp = new Response(ex.getCode(), ex.getMsg());
        resp.setRequestId(UUID.randomUUID().toString());
        response.getWriter().print(JSONUtil.toJsonStr(resp));
    }

    /**
     * 获取token
     * 优先从header获取
     * 如果没有，则从parameter获取
     * @param request request
     * @return token
     */
    private String getToken(HttpServletRequest request){
        String token = request.getHeader(X_TOKEN);
        if(ObjectUtils.isEmpty(token)){
            token = request.getParameter(X_TOKEN);
        }
        return token;
    }
}
